<template>
	<div>
		<a-form
			:wrapper-col="{ span: 16 }"
			:label-col="{ span: 8 }"
			autocomplete="off"
			labelAlign="right"
			ref="formRef"
			:model="formData"
			:rules="formRules"
		>
			<a-row>
				<a-col :span="12">
					<a-form-item label="销售方式" name="saleMethod">
						<a-select
							:disabled="props.disabled"
							placeholder="请选择销售方式"
							:options="tool.dictList('saleMethod')"
							v-model:value="formData.saleMethod"
						>
						</a-select>
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="选择项目" name="proId">
						<xn-page-selector
							:disabled="props.disabled"
							@change="proinfoChange"
							ref="proinfoRef"
							:field-names="{ label: 'name', value: 'id' }"
							:page-function="(param) => proinfo.proinfopage(param)"
							v-model:value="formData.proId"
							placeholder="请选择项目"
						>
						</xn-page-selector>
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="收入合同" name="contractId">
						<xn-page-selector
							ref="revenueContractRef"
							:disabled="props.disabled"
							@change="onContractChange"
							:page-function="
								(param) =>
									revenueContractApi.page(
										Object.assign(param, {
											types: '2'
										})
									)
							"
							v-model:value="formData.contractId"
							placeholder="请选择销售合同"
						>
						</xn-page-selector>
					</a-form-item>
				</a-col>
			</a-row>
			<a-row>
				<a-col :span="12">
					<a-form-item label="项目名称">
						<a-input disabled v-model:value="formData.proName" placeholder="请选择收入合同" />
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-form-item label="客户名称" name="customerId">
						<xn-page-selector
							:disabled="props.disabled"
							ref="customerRef"
							:field-names="{ label: 'custName', value: 'id' }"
							:page-function="(param) => customerApi.getPage(param)"
							v-model:value="formData.customerId"
							placeholder="请选择客户名称"
						>
						</xn-page-selector>
					</a-form-item>
				</a-col>
			</a-row>
			<a-row>
				<a-col :span="12">
					<a-form-item label="备注" name="remark">
						<a-input :disabled="props.disabled" v-model:value="formData.remark" placeholder="请输入备注" allow-clear />
					</a-form-item>
				</a-col>
			</a-row>

			<a-row>
				<a-col :span="24">
					<a-row>
						<a-col v-if="props.disabled">
							<a-button class="childAddButton"> 商品明细 </a-button>
						</a-col>
						<a-col v-else>
							<a-button type="primary" class="childAddButton" @click="addProduct()">
								<PlusOutlined />
								新增
							</a-button>
							<a-popconfirm title="是否删除?" @confirm="removeGoods()">
								<a-button style="margin-left: 12px" type="remove" danger>
									<LineOutlined />
									删除
								</a-button>
							</a-popconfirm>
						</a-col>
					</a-row>
					<a-table
						:row-selection="options.rowSelection"
						:pagination="false"
						:columns="goodsColumns"
						:data-source="formData.saleOrderDetailAddParamList"
						:scroll="{ x: 1000 }"
					>
						<template #bodyCell="{ index, record, column }">
							<template v-if="column.dataIndex === 'index'">
								<span>{{ index + 1 }}</span>
							</template>

							<template v-if="column.dataIndex === 'taxRate'">
								<a-input
									:disabled="props.disabled"
									@input="taxRateChange(record)"
									:style="{ width: column.width }"
									v-model:value="record.taxRate"
								/>
							</template>

							<template v-if="column.dataIndex === 'saleNum'">
								<a-input
									:disabled="props.disabled"
									@input="orderNumChange(record)"
									:style="{ width: column.width }"
									v-model:value="record.saleNum"
								/>
							</template>

							<template v-if="column.dataIndex === 'taxPrice'">
								<a-input
									:disabled="props.disabled"
									@input="taxChange(record)"
									:style="{ width: column.width }"
									v-model:value="record.taxPrice"
								/>
							</template>

							<template v-if="column.dataIndex === 'noTaxPrice'">
								<a-input
									:disabled="props.disabled"
									@input="excludingTaxChange(record)"
									:style="{ width: column.width }"
									v-model:value="record.noTaxPrice"
								/>
							</template>

							<template v-if="column.dataIndex === 'remark'">
								<a-input :disabled="props.disabled" :style="{ width: column.width }" v-model:value="record.remark" />
							</template>
						</template>
					</a-table>
				</a-col>
			</a-row>

			<div style="margin-top: 15px">
				<span style="color: #333; font-size: 16px; font-weight: 600">合计</span>
			</div>
			<a-row :gutter="24" style="margin-bottom: 50px; margin-top: 15px; margin-left: 20px">
				<a-col :span="8">
					<div style="margin-right: 12px; display: inline-block">
						<span>领料出库数量:</span>
					</div>
					<a-input style="width: 50%; border-radius: 5px" disabled placeholder="0" v-model:value="saleNum" />
				</a-col>
				<a-col :span="8">
					<div style="margin-right: 12px; display: inline-block">
						<span>含税总金额</span>
					</div>
					<a-input style="width: 50%; border-radius: 5px" disabled placeholder="0" v-model:value="taxAmount" />
				</a-col>
				<a-col :span="8">
					<div style="margin-right: 12px; display: inline-block">
						<span>不含税总金额</span>
					</div>
					<a-input style="width: 50%; border-radius: 5px" disabled placeholder="0" v-model:value="noTaxAmount" />
				</a-col>
			</a-row>
		</a-form>
		<system :value="{}"></system>
		<productSelector
			:data-provider="getOrderDetailList"
			:columns="selectorColumns"
			@onProductChange="onProductChange"
			ref="productsRef"
		/>
	</div>
</template>

<script setup name="dbsForm">
	import { required } from '@/utils/formRules'
	import productSelector from '@/components/Selector/productSelector.vue'
	import customerApi from '@/api/base_data/customerApi'
	import { message } from 'ant-design-vue'
	import { toRaw ,onMounted} from 'vue'
	import revenueContractApi from '@/api/contract/base/index'
	import xnPageSelector from '@/components/XnPageSelect/index.vue'
	import tool from '@/utils/tool'
	import contractpurmaterialApi from '@/api/purchasing/order/contractpurmaterialApi'
	import proinfo from '@/api/pm/pm/index'
	import system from '@/components/Task/system.vue'
	// 定义emit事件
	//PROCUREMENT_PARTNERS
	const emit = defineEmits({ successful: null })
	// 默认是关闭状态
	const productsRef = ref()
	const formRef = ref()
	const revenueContractRef = ref()
	const customerRef = ref()

	// 表单数据，也就是默认给一些数据
	const formData = ref({})
	const saleNum = ref(0)
	const proinfoRef = ref()
	const taxAmount = ref(0)
	const noTaxAmount = ref(0)

	const onContractChange = (id, item) => {
		formData.value.proInfoId = item.proId
		formData.value.proName = item.proName || item.proId
	}
	const props = defineProps({
		value: {
			type: Object,
			default: () => {}
		},
		disabled: {
			type: Boolean,
			default: () => false
		}
	})
	watch(
		() => props.value,
		(newVal, oldVal) => {
			if (newVal) {
				formData.value = { ...newVal }
				if (!formData.value.extJson) {
					return
				}
			}
		},
		{ deep: true, immediate: true }
	)

	onMounted(() => {
		if (!props.disabled) {
			nextTick(() => {
				customerRef.value.onPage({})
				proinfoRef.value.onPage({})
				revenueContractRef.value.onPage({})
			})
		}
	})

	const options = {
		rowSelection: {
			onChange: (selectedRowKey, selectedRows) => {
				selectedRowKeys.value = selectedRowKey
			}
		}
	}

	const removeGoods = () => {
		let datas = formData.value.saleOrderDetailAddParamList
		selectedRowKeys.value.forEach((element) => {
			let index = datas.findIndex((it) => {
				return it['id'] == element
			})
			if (index >= 0) {
				datas.splice(index, 1)
			}
		})
		selectedRowKeys.value = []
		taxAmount.value = totalTax()
		noTaxAmount.value = totalExcludingTaxTax()
		saleNum.value = totalOrderNum()
	}
	const selectedRowKeys = ref([])

	const formatPrice = (text) => {
		let value = text.match(/^\d*(\.?\d{0,2})/g)[0] || null
		if (isNaN(value)) {
			return ''
		}
		return value
	}

	const taxChange = (record) => {
		record.taxPrice = formatPrice(record.taxPrice)
		taxAmount.value = totalTax()
	}

	const excludingTaxChange = (record) => {
		record.noTaxPrice = formatPrice(record.noTaxPrice)
		noTaxAmount.value = totalExcludingTaxTax()
	}

	const orderNumChange = (record) => {
		let value = record.saleNum.replace(/[^\d]+/g, '')
		if (isNaN(value)) {
			record.saleNum = ''
		} else {
			record.saleNum = value
		}
		saleNum.value = totalOrderNum()
	}

	const taxRateChange = (record) => {
		let value = record.taxRate.replace(/[^\d]+/g, '')
		if (isNaN(value)) {
			record.taxRate = ''
		} else {
			record.taxRate = value
		}
	}
	const totalExcludingTaxTax = () => {
		let orderList = formData.value.saleOrderDetailAddParamList || []
		let amount = 0
		orderList.forEach((it) => {
			let noTaxPrice = it['noTaxPrice']
			if (noTaxPrice) {
				amount += parseFloat(noTaxPrice)
			}
		})
		return amount.toFixed(2).replace('.00', '')
	}
	const totalTax = () => {
		let orderList = formData.value.saleOrderDetailAddParamList || []
		let amount = 0
		orderList.forEach((it) => {
			let taxPrice = it['taxPrice']
			if (taxPrice) {
				amount += parseFloat(taxPrice)
			}
		})
		return amount.toFixed(2).replace('.00', '')
	}

	const totalOrderNum = () => {
		let orderList = formData.value.saleOrderDetailAddParamList || []
		let amount = 0
		orderList.forEach((it) => {
			let orderNum = it['saleNum']
			if (orderNum) {
				amount += parseInt(orderNum)
			}
		})
		return amount
	}

	const onProductChange = (items) => {
		let saleOrderDetailAddParamList = formData.value.saleOrderDetailAddParamList || []
		items.forEach((it) => {
			let find = saleOrderDetailAddParamList.find((item) => {
				return item['materialId'] == it['materialId']
			})
			if (find) {
				it = Object.assign(it, find)
			}
		})
		formData.value.saleOrderDetailAddParamList = items
	}

	const selectorColumns = [
		{
			title: '序号',
			dataIndex: 'index',
			ellipsis: true,
			width: 80,
			align: 'center'
		},
		{
			title: '产品编号',
			width: 100,
			dataIndex: 'code',
			align: 'center',
			ellipsis: true
		},
		{
			title: '产品名称',
			width: 120,
			dataIndex: 'name',
			align: 'center',
			ellipsis: true
		},
		{
			title: '品牌',
			width: 100,
			dataIndex: 'brand',
			align: 'center',
			ellipsis: true
		},
		{
			title: '规格',
			width: 100,
			dataIndex: 'spec',
			align: 'center',
			ellipsis: true
		},
		{
			title: '商品单价',
			width: 100,
			dataIndex: 'unitPrice',
			align: 'center',
			ellipsis: true
		}
	]

	// 默认要校验的
	const formRules = {
		saleMethod: [required('请选择销售方式')],
		contractId: [required('请选择合同')],
		customerId: [required('请选择客户')],
		settleMethod: [required('请选择结算方式')]
	}
	const addProduct = () => {
		if (!formData.value.contractId) {
			message.error('请选择合同')
			return
		}
		if (!formData.value.saleOrderDetailAddParamList) {
			formData.value.saleOrderDetailAddParamList = []
		}
		productsRef.value.showDialog(formData.value.saleOrderDetailAddParamList)
	}

	// 验证并提交数据
	const getData = () => {
		return new Promise((resolve, reject) => {
			submitApi()
				.then((data) => {
					resolve(data)
				})
				.catch((error) => {
					console.log(error)
					let msg = error.message
					if (msg) {
						message.error(msg)
					}
				})
		})
	}
	const submitApi = () => {
		return new Promise((resolve, reject) => {
			formRef.value
				.validate()
				.then(() => {
					let orderList = toRaw(formData.value.saleOrderDetailAddParamList) || []
					let msg = validatedField(orderList)
					if (msg) {
						reject(new Error(msg))
					} else {
						let params = { ...formData.value }
						let products = [].concat(orderList)
						if (formData.id) {
							params.saleOrderDetailEditParamList = products
						} else {
							params.saleOrderDetailAddParamList = products
						}
						params['flowCode'] = 'FLW_ENGINEER'
						Object.assign(params, {
							type: '工程',
							saleNum: saleNum.value,
							taxAmount: taxAmount.value,
							noTaxAmount: noTaxAmount.value
						})
						resolve(params)
					}
				})
				.catch((e) => reject(e))
		})
	}
	// 重置
	const resetForm = () => {
		formRef.value.resetFields()
	}
	// 调用这个函数将子组件的一些数据和方法暴露出去
	defineExpose({
		getData,
		resetForm
	})

	const validatedField = (orderList) => {
		if (orderList.length <= 0) {
			return '请添加商品'
		}
		let msg = null
		let itemRules = [
			{
				field: 'saleNum',
				error: '领料出库数量不能为空!'
			}
		]
		for (let i = 0; i < orderList.length; i++) {
			for (let rule of itemRules) {
				let item = orderList[i]
				let itemValue = item[rule['field']]
				if (!itemValue) {
					msg = `第${i + 1}行${rule['error']}`
					break
				}
			}
		}
		return msg
	}
	const getOrderDetailList = (parameter) => {
		return contractpurmaterialApi
			.getPage(
				Object.assign(parameter, {
					contractId: formData.value.contractId
				})
			)
			.then((res) => {
				res.forEach((it) => {
					it['name'] = it['material']['name']
					it['brand'] = it['material']['brand']
					it['spec'] = it['material']['spec']
					it['code'] = it['material']['code']
					it['unit'] = it['material']['unit']
					it['unitPrice'] = it['material']['unitPrice']
					it['key'] = it['id']
				})
				return {
					records: res,
					total: res.length,
					current: 1,
					pages: 10
				}
			})
			.catch(() => {})
	}

	const goodsColumns = [
		{
			title: '序号',
			width: 80,
			dataIndex: 'index',
			align: 'center'
		},
		{
			title: '产品编号',
			width: 120,
			dataIndex: 'code',
			align: 'center',
			ellipsis: true
		},
		{
			title: '产品名称',
			dataIndex: 'name',
			width: 180,
			align: 'center',
			ellipsis: true
		},
		{
			title: '单位',
			dataIndex: 'unit',
			width: 100,
			align: 'center'
		},
		{
			title: '规格型号',
			dataIndex: 'spec',
			width: 120,
			align: 'center'
		},
		{
			title: '领料出库数量',
			dataIndex: 'saleNum',
			width: 120,
			align: 'center'
		},
		{
			title: '税率',
			dataIndex: 'taxRate',
			width: 120,
			align: 'center'
		},
		{
			title: '含税金额',
			dataIndex: 'taxPrice',
			width: 120,
			align: 'center'
		},
		{
			title: '不含税金额',
			dataIndex: 'noTaxPrice',
			width: 140,
			align: 'center'
		},
		{
			title: '备注',
			dataIndex: 'remark',
			width: 200,
			align: 'center'
		}
	]
</script>

<style scoped :type="less">
	.childAddButton {
		margin-bottom: 10px;
	}
</style>
